package com.changanw.tienchin.framework.config;

import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;

/**
 * @author changanw
 * @version ncc1.0   自定义权限表达式，使用 @hasPermission 等注解，此时走的是自己自定义的权限匹配
 * @description TODO
 * @date 2023/7/4 19:43
 */
public class CustomerSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {
  private Object filterObject;
  private Object returnObject;
  //这是一个ant风格的匹配器，可以使用通配符进行匹配，解决equals方法全字符串匹配的问题
  private AntPathMatcher antPathMatcher = new AntPathMatcher();
  public CustomerSecurityExpressionRoot(Authentication authentication) {
    super(authentication);
  }
  public boolean hasPermission(String permission){
    //获取用户的所有权限
    //这里调用的其实是com.changanw.tienchin.common.core.domain.model.LoginUser.getAuthorities的方法的返回值
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority authority : authorities) {
      if (antPathMatcher.match(authority.getAuthority(),permission)){
        return true;
      }
    }
    return false;
  }
  public boolean hasAnyPermissions(String... permissions){
    if (permissions == null || permissions.length == 0){
      return false;
    }
    //获取用户的所有权限
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (GrantedAuthority authority : authorities) {
      for (String permission : permissions) {
        if (antPathMatcher.match(authority.getAuthority(),permission)){
          return true;
        }
      }

    }
    return false;
  }
  public boolean hasAllPermissions(String... permissions){
    if (permissions == null || permissions.length == 0){
      return false;
    }
    //获取用户的所有权限
    Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
    for (String permission : permissions) {
      boolean flag = false;
      for (GrantedAuthority authority : authorities) {
        if (antPathMatcher.match(authority.getAuthority(),permission)){
          flag = true;
        }
      }
      //如果有一个权限没有匹配上，说明不具备所有的权限，返回false
      if (!flag){
        return false;
      }
    }
    return true;
  }


  @Override
  public void setFilterObject(Object filterObject) {
    this.filterObject = filterObject;
  }

  @Override
  public Object getFilterObject() {
    return filterObject;
  }

  @Override
  public void setReturnObject(Object returnObject) {
    this.returnObject = returnObject;
  }

  @Override
  public Object getReturnObject() {
    return returnObject;
  }

  @Override
  public Object getThis() {
    return this;
  }
}
